const axios = require('axios')
const xbogus = require('xbogus')
const mapValuesLimit = require('async/mapValuesLimit');

function getVideo(vid) {

  const url = "https://www.douyin.com/aweme/v1/web/aweme/detail/?aweme_id=" + vid + '&aid=1128&version_name=23.5.0&device_platform=android&os_version=2333'

  const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';

  const xbogusStr = xbogus(url, userAgent)

  return axios({
    url: url + '&X-Bogus=' + xbogusStr,
    headers: {
      'User-Agent': userAgent,
      Referer: 'https://www.douyin.com/',
      'Cookie': 'msToken=tc1uoTeHMp-EZDolPP-OiqYS-RglukWxIeRTlANTLdGnZWwXYKReqeoR-OMkX3E_u8N1Gt-VGJ1wKo9bDWaWlyK3hcQMA7AA2d35etqcXDJpY4AJxFldK1yZYGOwPd7t;ttwid=1%7CWBuxH_bhbuTENNtACXoesI5QHV2Dt9-vkMGVHSRRbgY%7C1677118712%7C1d87ba1ea2cdf05d80204aea2e1036451dae638e7765b8a4d59d87fa05dd39ff;'
    },
  })

}

// 获取评论
function getComments(vid) {

  const url = "https://www.douyin.com/aweme/v1/web/comment/list/?aweme_id=" + vid + '&aid=1128&version_name=23.5.0&device_platform=android&os_version=2333&count=50'

  const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';

  const xbogusStr = xbogus(url, userAgent)

  return axios({
    url: url + '&X-Bogus=' + xbogusStr,
    headers: {
      'User-Agent': userAgent,
      Referer: 'https://www.douyin.com/video/' + vid,
      'Cookie': 'msToken=tc1uoTeHMp-EZDolPP-OiqYS-RglukWxIeRTlANTLdGnZWwXYKReqeoR-OMkX3E_u8N1Gt-VGJ1wKo9bDWaWlyK3hcQMA7AA2d35etqcXDJpY4AJxFldK1yZYGOwPd7t;ttwid=1%7CWBuxH_bhbuTENNtACXoesI5QHV2Dt9-vkMGVHSRRbgY%7C1677118712%7C1d87ba1ea2cdf05d80204aea2e1036451dae638e7765b8a4d59d87fa05dd39ff;'
    },
  })

}

// 获取单条评论的回复
function getReply(vid, commentId) {
  const url = "https://www.douyin.com/aweme/v1/web/comment/list/reply/?item_id=" + vid + '&aid=1128&version_name=23.5.0&device_platform=android&os_version=2333&comment_id=' + commentId + '&count=50'

  const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';

  const xbogusStr = xbogus(url, userAgent)

  return axios({
    url: url + '&X-Bogus=' + xbogusStr,
    headers: {
      'User-Agent': userAgent,
      Referer: 'https://www.douyin.com/',
      'Cookie': 'msToken=tc1uoTeHMp-EZDolPP-OiqYS-RglukWxIeRTlANTLdGnZWwXYKReqeoR-OMkX3E_u8N1Gt-VGJ1wKo9bDWaWlyK3hcQMA7AA2d35etqcXDJpY4AJxFldK1yZYGOwPd7t;ttwid=1%7CWBuxH_bhbuTENNtACXoesI5QHV2Dt9-vkMGVHSRRbgY%7C1677118712%7C1d87ba1ea2cdf05d80204aea2e1036451dae638e7765b8a4d59d87fa05dd39ff;'
    },
  })
}

// 获取批量回复的评论
function batchGetReply(vid, replyCommentIds) {
  return new Promise((resolve, reject) => {
    mapValuesLimit(replyCommentIds, 10, (cid, key, callback) => {
      getReply(vid, cid, 50).then(replayResponse => {
        if (replayResponse.status === 200 && replayResponse.data.status_code === 0) {
          let replyText = ''
          replayResponse.data.comments.forEach(reply => {
            replyText += reply.text + "。"
          })
          return callback(null, {
            cid,
            text: replyText,
          })
        }
        callback({
          cid,
          error: `获取回复评论失败：code:${replayResponse.data.status_code}`
        })
      }).catch(error => {
        return callback({
          cid,
          error: `获取回复评论失败：${error}`
        })
      })
    }, (error, result) => {
      if (error) {
        console.log('error', error)
        reject(error)
      } else {
        let replyCommentText = ''
        for (const key in result) {
          replyCommentText += result[key].text
        }
        resolve(replyCommentText)
      }
    })
  })
}

// 下载视频
exports.getVideoController = async (ctx) => {

  const { vid } = ctx.request.query

  if (vid) {
    try {
      const res = await getVideo(vid)
      if (res.status === 200 && res.data.status_code === 0) {
        ctx.status = 200
        ctx.body = {
          code: 200,
          msg: 'success',
          data: res.data.aweme_detail
        }
      } else {
        throw new Error('获取失败')
      }
    } catch (error) {
      console.log(error)
      ctx.status = 500
      ctx.body = {
        code: 500,
        msg: '服务错误',
        error
      }
    }
    return
  }
  ctx.status = 400
  ctx.body = {
    code: 400,
    msg: 'vid不能为空'
  }
}

// 获取视频Top 50 评论及其回复
exports.getTopCommentsController = async function (ctx) {
  const { vid } = ctx.request.query
  if (vid) {
    try {
      const topCommentResponse = await getComments(vid)
      if (topCommentResponse.status === 200 && topCommentResponse.data.status_code === 0) {
        // 所有评论内容
        let commentText = ''
        // 将评论点赞数从高到低排序
        const topCommentList = topCommentResponse.data.comments.sort((i, j) => j.digg_count - i.digg_count)
        // 如果这条评论有回复，再获取回复内容
        const replyCommentIds = []
        topCommentList.forEach(c => {
          commentText += c.text + "。"
          if (c.reply_comment_total > 0) {
            replyCommentIds.push(c.cid)
          }
        })
        const replyCommentText = await batchGetReply(vid, replyCommentIds)
        const allCommentText = commentText + replyCommentText
        ctx.status = 200
        ctx.body = {
          code: 200,
          msg: 'success',
          data: allCommentText.replace(/(\[.+?\])|(@.+? )/g, '')
        }
      } else {
        throw new Error('获取失败')
      }
    } catch (error) {
      ctx.status = 500
      ctx.body = {
        code: 500,
        msg: '服务错误',
        error
      }
    }
    return
  }

  ctx.status = 400
  ctx.body = {
    code: 400,
    msg: 'vid不能为空'
  }

}